package com.eastedu.manager;

import cn.hutool.core.collection.CollUtil;
import com.eastedu.client.file.FileClient;
import com.eastedu.client.file.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * The type File manager.
 *
 * @author zhangzhishuai
 */
@Slf4j
@Service
public class FileManagerImpl implements FileManager {
    /**
     * 文件服务提供商
     * 腾讯
     */
    public static final String FILE_PROVIDER_TENCENT = "tencent";
    private final FileClient fileClient;

    public FileManagerImpl(FileClient fileClient) {
        this.fileClient = fileClient;
    }

    @Override
    public String getDownloadUrl(Long fileId) {
        return Optional.ofNullable(fileId)
                .map(this.fileClient::get)
                .map(FileInfoResponse::getUrls)
                .map(FileInfoResponse.UrlsDTO::getDownload)
                .orElse(null);
    }

    @Override
    public FileInfoResponse getFileInfoByMd5(String md5) {
        return Optional.ofNullable(md5)
                .map(v -> fileClient.listFileByMd5(FILE_PROVIDER_TENCENT, Collections.singletonList(v)))
                .flatMap(list -> list.stream().findFirst())
                .orElse(null);
    }

    @Override
    public FileInfoResponse getFileInfo(Long fileId) {
        return Optional.ofNullable(fileId)
                .map(this.fileClient::get)
                .orElse(null);
    }

    @Override
    public boolean fileArchive(Set<String> fileIds) {
        if (CollUtil.isEmpty(fileIds)) {
            return true;
        }
        FileFunctionResponse fileFunctionResponse = fileClient.functionArchive(FILE_PROVIDER_TENCENT, FileArchiveRequest.builder().files(new ArrayList<>(fileIds)).build());
        return !Optional.ofNullable(fileFunctionResponse)
                .map(FileFunctionResponse::getResult)
                .map(Map::values)
                .map(v -> v.stream().anyMatch("0"::equals))
                .orElse(false);

    }

    @Override
    public FileSignatureResponse postFileSignature(FileSignatureRequest fileSignatureRequest) {
        return this.fileClient.postFileSignature(fileSignatureRequest);
    }

    @Override
    public void putFile(String fileId, FileUpdateRequest fileUpdateRequest) {
        this.fileClient.putFile(fileId, fileUpdateRequest);
    }

    @Override
    public void restore(List<String> fileIds) {
        this.fileClient.restore(new FileRestoreRequest(fileIds, 7));
    }
}
